﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace UploadServer.FrontEndDemo.Util
{
    public class JwtTokenHelper
    {
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string GenerateJwtToken(string userId, string username)
        {
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey00000000000"));
            var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "yourIssuer",
                audience: "yourAudience",
                claims: new Claim[]
                {
                new Claim(JwtRegisteredClaimNames.Sub, userId),
                new Claim(JwtRegisteredClaimNames.UniqueName, username)
                },
                expires: DateTime.Now.AddHours(1),
                signingCredentials: signinCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);

            //var tokenHandler = new JwtSecurityTokenHandler();
            //var key = Encoding.ASCII.GetBytes("YourSecretKey000000000000000000000");

            //var tokenDescriptor = new SecurityTokenDescriptor
            //{
            //    Subject = new ClaimsIdentity(new[] { new Claim("id", "123456") }),
            //    Expires = DateTime.UtcNow.AddDays(7),
            //    SigningCredentials =
            //        new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            //};
            //var token = tokenHandler.CreateToken(tokenDescriptor);
            //return tokenHandler.WriteToken(token);

        }
        /// <summary>
        /// 生成上传token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string UploadJwtToken(string secretKey)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(secretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { 
                    new Claim("app", "test"),
                    new Claim("size", "25mb")
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
        /// <summary>
        /// 验证token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool ValidateToken(string token)
        {
            //string token = "YourTokenHere"; // 要验证的JWT
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "yourIssuer", // Token的颁发者
                ValidAudience = "yourAudience", // Token的受众
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey00000000000")) // 用于签名的密钥
            };
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);

                // 如果验证成功，principal对象包含Token中的Claims
                if (principal != null)
                {
                    // Token验证成功，可以进一步处理principal中的Claims
                    return true;
                }
                else
                {
                    // Token验证失败
                    return false;
                }
            }
            catch (Exception ex)
            {
                // Token验证过程中发生异常
                Console.WriteLine($"Token validation failed: {ex.Message}");
                return false;
            }          
        }
    }
}
